const userDao = require('../dao/userDao');
const { checkUserName, checkUserInfo } = require('../middleware/checkUserInfo')


module.exports = {
    checkUsername: async ctx => {
        const { userName } = ctx.request.query;
        console.log('object', userName)
        // 校验用户名是否满足条件
        if (!checkUserName(ctx, userName)) return
        console.log(!checkUserName(userName))
        const num = await userDao.checkUsername(userName);
        console.log("object", num)
        if (!!num) {
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '0',
                    msg: '用户名不存在，可以注册'
                }
            }
        } else {
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '1',
                    msg: '用户名已存在'
                }
            }
        }

    },
    register: async ctx => {
        const { userName, passWord } = ctx.request.body;
        const result = await userDao.register(userName, passWord);
        console.log('result', result)
        if (result.affectedRows === 1) {
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '0',
                    msg: '注册成功'
                }
            }
        } else {
            ctx.body = {
                status: 500,
                message: '注册失败'
            }
        }
    },
    login: async ctx => {
        const { userName, password } = ctx.request.body;
        // 检验前端传递过来的值是否符合规则
        if (!checkUserInfo(ctx, userName, password)) return;
        try {
            const user = await userDao.login(userName, password);
            console.log("object",user)
            if (!user) {
                ctx.body = {
                    status: 80200,
                    message: 'success',
                    data: {
                        code: '4',
                        msg: '用户名或密码错误'
                    }
                }
                return
            }
            const userInfo = {
                user_id: user[0].user_id,
                userName: user[0].userName
            }
            // 将用户信息存储到session
            ctx.session.user = userInfo
            ctx.body = {
                status: 80200,
                message: "success",
                data: {
                    code: '0',
                    msg: '登录成功',
                    data: userInfo
                }
            }
        } catch (error) {
            console.log(error)
            ctx.body = {
                status: 80200,
                message: 'success',
                data: {
                    code: '500',
                    msg: "系统错误，请重试"
                }
            }
        }

    }
}